<template>
  <el-card class="box-card">
    <!--  新增弹出框  -->
    <el-dialog title="新增角色"
               :visible.sync="dialogVisible"
               width="40%"
               :before-close="handleClose">

      <el-form :model="roleForm" :rules="roleFormRules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="path">
          <el-input v-model="roleForm.description"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="roleForm.orderNum"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="isDisable">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddForm('roleForm')">立即创建</el-button>
          <el-button @click="resetForm('roleForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!--  修改弹出框  -->
    <el-dialog title="修改角色信息"
               :visible.sync="dialogUpdate"
               width="40%"
               :before-close="handleCloseUpdate">
      <el-form :model="roleForm" :rules="roleFormRules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" disabled></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="path">
          <el-input v-model="roleForm.description"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="roleForm.orderNum"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="isDisable">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitUpdateForm('roleForm')">立即修改</el-button>
          <el-button @click="resetForm('roleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  分配菜单弹出框  -->
    <el-dialog title="分配菜单"
               :visible.sync="dialogMenu"
               width="40%"
               :before-close="handleCloseMenu">
      <el-form :model="menuForm">
        <div style="margin-bottom: 15px">
          <el-button type="primary" size="small" @click="handleCheckAllMenu">全选/取消全选</el-button>
        </div>
        <el-tree
            :data="menuTreeData"
            show-checkbox
            ref="menuTree"
            node-key="id"
            :default-expand-all="true"
            :props="defaultProps">
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer">
			    <el-button @click="dialogMenu = false">取 消</el-button>
			    <el-button type="primary" @click="submitMenuFormHandle('menuForm')">确 定</el-button>
			</span>
    </el-dialog>

    <!--  分配权限弹出框  -->
    <el-dialog title="分配权限"
               :visible.sync="dialogPermission"
               width="40%"
               :before-close="handleClosePermission">
      <el-form :model="permissionForm">
        <div style="margin-bottom: 15px">
          <el-button type="primary" size="small" @click="handleCheckAllPermission">全选/取消全选</el-button>
        </div>
        <el-tree
            :data="permissionTreeData"
            show-checkbox
            ref="permissionTree"
            node-key="id"
            :default-expand-all="true"
            :check-strictly="true"
            :props="defaultProps">
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer">
			    <el-button @click="dialogPermission = false">取 消</el-button>
			    <el-button type="primary" @click="submitPermissionFormHandle('permissionForm')">确 定</el-button>
			</span>
    </el-dialog>

    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">
        <el-form-item>
          <my-select v-model="condition.status"
                     placeholder="请选择状态"
                     :showList="condition.statusList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.keywords"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入角色关键字"
              style="width:200px"
              @keyup.enter.native="searchRoles"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchRoles">
            搜索
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogVisible = true">新增</el-button>
        </el-form-item>


        <el-form-item>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                     :disabled="this.selection.length === 0">删除选中
          </el-button>
        </el-form-item>

      </el-form>
    </div>

    <!--  表格内容  -->
    <el-table ref="multipleTable"
              :data="tableData"
              border
              highlight-current-row
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="角色名称" width="200"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="orderNum" label="排序序号" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" sortable width="150">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(scope.row.id,scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="编辑" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="分配菜单" placement="top-start">
            <el-button circle icon="el-icon-s-operation" size="mini" @click="menuEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="分配权限" placement="top-start">
            <el-button circle icon="el-icon-setting" size="mini" @click="permissionEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" placement="top-start" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

  </el-card>
</template>

<script>
import { roleApi } from '@/api';
import { getAdminMenuList as getMenuList } from '@/api/menu';
import { permissionApi } from '@/api';

export default {
  data() {
    return {
      tableData: [],
      menuTreeData: [],
      permissionTreeData: [],
      roleForm: {},
      menuForm: {},
      permissionForm: {},
      roleId: '',
      total: 0,
      pageNum: 1,
      pageSize: 10,
      selection: [],
      selectedNum: 0,
      dialogVisible: false,
      dialogUpdate: false,
      dialogMenu: false,
      dialogPermission: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      condition: {
        keywords: null,
        status: null,
        statusList: [
          {
            value: 0,
            label: "禁用"
          },
          {
            value: 1,
            label: "启用"
          }
        ]
      },
      roleFormRules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
      }
    }
  },


  methods: {
    /**
     * 提交新增表单
     * @param forName
     */
    submitAddForm(forName) {
      this.$refs[forName].validate(valid => {
        if (valid) {
          let data = this.roleForm;
          roleApi.addRole(data).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadMenuList()
                }
              });
              this.dialogVisible = false;
              this.loadRoleList();
            }
          })
        } else {
          alert('请完整填写表单!');
          return false;
        }
      })
    },

    /**
     * 提交修改表单
     * @param forName
     */
    submitUpdateForm(forName) {
      this.$refs[forName].validate(valid => {
        if (valid) {
          let data = this.roleForm;
          roleApi.updateRole(data).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadMenuList()
                }
              });
              this.dialogUpdate = false;
              this.loadRoleList();
            }
          })
        } else {
          alert('请完整填写表单!');
          return false;
        }
      })
    },

    /**
     * 获取菜单列表
     */
    loadMenuList() {
      getMenuList().then((response) => {
        if (response.data.code === 20000) {
          this.menuTreeData = response.data.data;
        }
      })
    },

    /**
     * 分配菜单按钮事件,获取角色相关菜单
     * @param id 数据id
     */
    menuEdit(id) {
      roleApi.getRoleMenuIds(id).then(response => {
        if (response.data.code === 20000) {
          //将当前角色对应的菜单回显到对话框中(获取与角色相关联的菜单id)
          let menuIds = response.data.data;
          this.dialogMenu = true;
          this.roleId = id;
          this.$nextTick(() => {
            this.$refs.menuTree.setCheckedKeys(menuIds);
          });
        }
      })
    },

    /**
     * 提交菜单分配表单
     *  @param formName 表单数据
     */
    submitMenuFormHandle(formName) {
      //获取tree中被选中节点的key所组成的数组
      const menuIds = this.$refs.menuTree.getCheckedKeys();
      console.log("选中菜单id为：", menuIds);

      let roleId = this.roleId;
      console.log("选中的roleId：", roleId);

      roleApi.assignMenuToRole(roleId, menuIds).then(response => {
        if (response.data.code === 20000) {
          this.$message({
            showClose: true,
            message: "操作成功！",
            type: 'success',
            onClose: () => {
              this.loadRoleList()
            }
          });
          this.dialogMenu = false;
          this.resetForm(formName);
        }
      })
    },

    /**
     * 获取权限树列表
     */
    loadPermissionList() {
      permissionApi.getPermissionListTree().then((response) => {
        if (response.data.code === 20000) {
          this.permissionTreeData = response.data.data;
        }
      })
    },

    /**
     * 分配权限按钮事件,获取角色相关权限
     * @param id 数据id
     */
    permissionEdit(id) {
      this.dialogPermission = true;
      this.roleId = id;
      
      // 确保在每次打开对话框前重置树组件的选中状态
      if (this.$refs.permissionTree) {
        this.$refs.permissionTree.setCheckedKeys([]);
      }
      
      roleApi.getRolePermissionIds(id).then(response => {
        if (response.data.code === 20000) {
          //将当前角色对应的权限回显到对话框中(获取与角色相关联的权限id)
          let permissionIds = response.data.data || [];
          
          this.$nextTick(() => {
            this.$refs.permissionTree.setCheckedKeys(permissionIds);
          });
        }
      })
    },

    /**
     * 提交权限分配表单
     *  @param formName 表单数据
     */
    submitPermissionFormHandle(formName) {
      //获取tree中被选中节点的key所组成的数组
      const permissionIds = this.$refs.permissionTree.getCheckedKeys();
      console.log("选中权限id为：", permissionIds);

      let roleId = this.roleId;
      console.log("选中的roleId：", roleId);

      roleApi.assignPermissionToRole(roleId, permissionIds).then(response => {
        if (response.data.code === 20000) {
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success',
            onClose: () => {
              this.loadRoleList()
            }
          });
          this.dialogPermission = false;
          this.resetForm(formName);
        }
      })
    },

    /**
     * 启用/禁用角色
     */
    changeStatus(id, status) {
      this.roleForm.id = id
      this.roleForm.status = status
      roleApi.updateRole(this.roleForm).then((response) => {
        if (response.data.code === 20000) {
          this.$message.success("修改成功！")
          this.loadRoleList();
        }
      })
    },

    /**
     * 关闭新增dialog
     */
    handleClose() {
      if (this.$refs.form !== undefined) this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.roleForm = {};
    },

    /**
     * 关闭修改dialog
     */
    handleCloseUpdate() {
      this.resetForm("handleEdit");
      this.dialogUpdate = false;
    },

    /**
     * 关闭分配菜单dialog
     */
    handleCloseMenu() {
      this.dialogMenu = false;
    },

    /**
     * 关闭分配权限dialog
     */
    handleClosePermission() {
      this.dialogPermission = false;
      // 清空权限树的选中状态
      if (this.$refs.permissionTree) {
        this.$refs.permissionTree.setCheckedKeys([]);
      }
    },

    // 重置弹出框内容
    resetForm(formName) {
      if (this.$refs.form !== undefined) this.$refs.form.resetFields();
      this.roleForm = {};
    },

    /**
     * 将当前行角色信息数据回显到弹出表单中，并打开表单
     * @param id 数据id
     */
    handleEdit(id) {
      roleApi.getRoleInfo(id).then((response) => {
        if (response.data.code === 20000) {
          this.roleForm = response.data.data;
          this.dialogUpdate = true;
        }
      })
    },

    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadRoleList();
    },

    /**
     * 搜索框事件
     */
    searchRoles() {
      this.pageNum = 1;
      this.loadRoleList();
    },

    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("删除后不可恢复", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        roleApi.deleteRoles(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message.success("角色删除成功！")
          }
          this.loadRoleList();
        });
      })
    },

    /**
     * 查询角色列表
     */
    loadRoleList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        status: this.condition.status,
        keywords: this.condition.keywords
      };
      
      roleApi.getRoleList(params).then((response) => {
        if (response.data.code === 20000) {
          if (response.data.data != null) {
            this.tableData = response.data.data.pagingList;
            this.total = response.data.data.count;
            return;
          }
          this.tableData = null;
          this.total = null;
        }
      });
    },

    /**
     * 处理权限全选/取消全选
     */
    handleCheckAllPermission() {
      const allNodes = this.$refs.permissionTree.getCheckedNodes(false, true);
      if (allNodes.length > 0) {
        // 如果有选中的节点，则取消全选
        this.$refs.permissionTree.setCheckedNodes([]);
      } else {
        // 如果没有选中的节点，则全选
        const allKeys = [];
        const getKeys = (data) => {
          data.forEach(item => {
            allKeys.push(item.id);
            if (item.children && item.children.length > 0) {
              getKeys(item.children);
            }
          });
        };
        getKeys(this.permissionTreeData);
        this.$refs.permissionTree.setCheckedKeys(allKeys);
      }
    },

    /**
     * 处理菜单全选/取消全选
     */
    handleCheckAllMenu() {
      const allNodes = this.$refs.menuTree.getCheckedNodes(false, true);
      if (allNodes.length > 0) {
        // 如果有选中的节点，则取消全选
        this.$refs.menuTree.setCheckedNodes([]);
      } else {
        // 如果没有选中的节点，则全选
        const allKeys = [];
        const getKeys = (data) => {
          data.forEach(item => {
            allKeys.push(item.id);
            if (item.children && item.children.length > 0) {
              getKeys(item.children);
            }
          });
        };
        getKeys(this.menuTreeData);
        this.$refs.menuTree.setCheckedKeys(allKeys);
      }
    },

  },


  created() {
    this.loadRoleList();
    this.loadMenuList();
    this.loadPermissionList();
  }
}


</script>

<style scoped>

</style>